import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

interface JwtUserInfo {
  id: number;
  username: string;
  email: string;
  roles: string[];
  permissions: string[];
}

declare module 'express' {
  interface Request {
    user: JwtUserInfo;
  }
}

@Injectable()
export class LoginGuard implements CanActivate {
  @Inject()
  private readonly reflector: Reflector;

  @Inject(JwtService)
  private readonly JwtService: JwtService;
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requireLogin = this.reflector.getAllAndOverride<boolean>(
      'require-login',
      [context.getHandler(), context.getClass()],
    );
    // 如果没有设置requireLogin，不需要登录，直接放行
    if (!requireLogin) {
      return true;
    }
    const request: Request = context.switchToHttp().getRequest();
    const token = request.headers.authorization?.split(' ')[1];
    // 没有token则未登录
    if (!token) {
      throw new UnauthorizedException('请先登录');
    }
    try {
      // 验证token
      const jwtUserInfo: JwtUserInfo = await this.JwtService.verify(token);
      console.log('aaa', jwtUserInfo);
      request.user = jwtUserInfo;
      return true;
    } catch (e) {
      throw new UnauthorizedException('登录已过期，请重新登录');
    }
  }
}
